import { createRouter, createWebHashHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import Layout from '@/layout/Layout.vue'
//配置路由地址和路由组件对应关系
const routes = [
    {
        path: '/layout',
        component: Layout,
        redirect: '/layout/home',
        children: [
            {
                path: '/layout/home',
                component: () => import('@/views/Home/index.vue')
            },
            {
                path: '/layout/city',
                component: () => import('@/views/Citys/index.vue')
            },
            {
                path: '/layout/spot',
                component: () => import('@/views/Spot/index.vue')
            },
            {
                path: '/layout/article/:categoryId?',
                component: () => import('@/views/Article/index.vue')
            },
            {
                path: '/layout/about',
                component: () => import('@/views/About/index.vue')
            },
            {
                path: '/layout/image',
                component: () => import('@/views/Image/index.vue')
            },
            {
                path: '/layout/citydetail/:cityId?',
                component: () => import('@/views/Citys/citydetail.vue')
            },
            {
                path: '/layout/spotdetail/:spotId?',
                component: () => import('@/views/Spot/spotdetail.vue')
            },
            {
                path: '/layout/articledetail/:articleId?',
                component: () => import('@/views/Article/articledetail.vue')
            },
            {
                path: '/layout/contract',
                component: () => import('@/views/Contract/index.vue')
            },
            {
                path: '/layout/tourist',
                component: () => import('@/views/Tourist/index.vue')
            }
        ]
    },
    {
        path: '/login',
        component: () => import('@/views/Login/index.vue')
    },
    {
        path: '/addArticle',
        component: () => import('@/views/Article/addArticle.vue')
    },
    {
        path: '/person',
        component: () => import('@/views/Person/index.vue')
    },
    {
        path: '/',
        component: () => import('@/views/Welcome/index.vue')
    }
]

//创建路由实列 导入配置项
const router = createRouter({
    routes,
    history: createWebHashHistory()
})


const blackList = ['/addArticle', '/person']
router.beforeEach(async (to, from, next) => {
    let token = localStorage.getItem("token")
    if (token) {
        if (to.path == '/login') {
            next('/layout/home')
            return;
        }
        next()
    }
    else {
        if (blackList.includes(to.path)) {
            ElMessage.error("请登录")
            next('/login')
            return
        }
        else {
            next()
        }
    }
})
//到处路由实列
export default router